/*
 * gTranslate.cpp
 *
 *  Created on: 16.08.2009
 *      Author: index01d
 */

#include "gTranslate.h"

gTranslate::gTranslate()
{
	mManager = new QNetworkAccessManager();
	mFrom = "en";
	mTo = "ru";
	fillLangs();
	connect(mManager, SIGNAL(finished(QNetworkReply*)),this, SLOT(translateFinished(QNetworkReply*)));
}

gTranslate::~gTranslate()
{
	delete mManager;
}

void gTranslate::translateString(const QString& text)
{
    QUrl *url = new QUrl("http://www.google.com/translate_t?hl=en&ie=UTF8&text="+text+"&langpair="+mFrom+"|"+mTo);
    mManager->get(QNetworkRequest(*url));
    delete url;
}

void gTranslate::translateFinished(QNetworkReply *reply)
{
	//Start of google translate Parser!
	QByteArray array = reply->readAll();
	QByteArray begin = "<div id=result_box";

	//TODO: Error handler
	if(!array.contains(begin))
	{
	   //we have some problem
	   return;
	}

    int index = array.indexOf(begin);

    QByteArray result;
    int i = index+29;
    bool end = false;
    while(end == false)
    {
        QString a(array.at(i));
        QString t("<");
        if(a == t)
        {
	        end = true;
	        break;
	    }
	    result.append(array.at(i));
	    ++i;
	}

	result.replace("&#39;","'");

	//Preparing for QString
	QTextCodec *codes = QTextCodec::codecForName("UTF-8");
	QString r = codes->toUnicode(result);

	emit tReady(r);
}

void gTranslate::setLangs(const QString& from, const QString& to)
{
	mFrom = from;
	mTo = to;
}

QStringList gTranslate::getLangs()
{
	return mLangs;
}

void gTranslate::fillLangs()
{
	mLangs << "en"
	    <<"de"
	    <<"ar"
	    <<"bg"
	    <<"ca"
	    <<"zh-CN"
	    <<"ko"
	    <<"hr"
	    <<"da"
	    <<"es"
	    <<"fi"
	    <<"fr"
	    <<"el"
	    <<"iw"
	    <<"hi"
	    <<"id"
	    <<"it"
	    <<"ja"
	    <<"lv"
	    <<"lt"
	    <<"nl"
	    <<"no"
	    <<"pl"
	    <<"pt"
	    <<"ro"
	    <<"ru"
	    <<"sr"
	    <<"sk"
	    <<"sl"
	    <<"sv"
	    <<"tl"
	    <<"cs"
	    <<"uk";
}
